import { ArkFile, AstTreeUtils } from "arkanalyzer";
import { ts } from "qvog-dsl";
import { AstMatcher, AstMatcherCallback } from "../Matchers";

export function matchAst(arkFiles: ArkFile[], matchers: [AstMatcher, AstMatcherCallback][]): void {
    for (let arkFile of arkFiles) {
        iterateAst(arkFile, matchers);
    }
}

function iterateAst(arkFile: ArkFile, matchers: [AstMatcher, AstMatcherCallback][]): void {
    const root = AstTreeUtils.getSourceFileFromArkFile(arkFile);
    root.forEachChild((node => {
        matchAstNode(node as any, matchers);
    }));
}

function matchAstNode(node: ts.Node, matchers: [AstMatcher, AstMatcherCallback][]): void {
    for (const [matcher, callback] of matchers) {
        if (matcher.match(node)) {
            callback(node);
        }
    }
    node.forEachChild((child: ts.Node) => {
        matchAstNode(child, matchers);
    });
}